package com.example.srpingsecurityoauth2.config;

import io.swagger.models.HttpMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

/**
 * @ClassName AuthorizationServerConfig
 * @Description 授权服务器配置
 * @Author gqz
 * @Date 2021/12/30 15:49
 * @Version 1.0
 **/
@Configuration
//开启授权服务器
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Value("${oauth2.client.id}")
    private String clientId;

    @Value("${oauth2.client.scope}")
    private String scope;

    @Value("${oauth2.client.secret}")
    private String secret;

    @Value("${oauth2.client.access-token-validity-seconds}")
    private int accessTokenValiditySeconds;

    @Value("${oauth2.client.registered-redirect-uri}")
    private String redirectUri;

    @Value("${oauth2.client.type}")
    private String type;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    //配置密码模式
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //配置client-id
                .withClient(clientId)
                //配置client-secret
                .secret(passwordEncoder.encode(secret))
                //配置访问token的有效期（一小时）
                .accessTokenValiditySeconds(accessTokenValiditySeconds)
                //配置重定向的地址,用于授权成功后跳转
                .redirectUris(redirectUri)
                //配置申请的权限范围
                .scopes(scope)
                //配置授权类型(这里用的是授权码模式)
                .authorizedGrantTypes(type);
    }


}
